#include <stdio.h>
#include "player.h"
#include "game.h"
#include "shot.h"
#include "databank.h"
#include "common.h"

void GameModule::turnRevolve()
{
	if(gameType == GAME_DEMO) {
		// Special stuff for demo processing
		if( (frameCount % (FPS*2)) == 0) {
			double pos[2] = {frand()*double(dataBank->getconfig()->screenWidth), frand()*double(dataBank->getconfig()->screenWidth) };
			double vel[2] = {0.0,0.0};
			dataBank->makeShot(new Shot(dataBank, ShotType(rand()%SHOT_MAX), pos, vel));
		}
		
		return;
	}
	
	if(dataBank->getPlayerAlive() <= 0) {
		turnStatus = TURN_PARTICLE;
	}
	
	switch(turnStatus) {
		case TURN_PLAYER:
			if(curPl->process(delta) == TURN_FINISHED || !curPl->alive()) {
				// Must've fired, get weapon
				curWeapon = curPl->curWeapon();
				
				turnStatus = TURN_WEAPON;
				speedTimer = 10.0;
			}
		break;
	
		case TURN_WEAPON:
			if(curWeapon != NULL) {
				if(curWeapon->doFire(curWeapon, curPl, delta)) {
					turnStatus = TURN_SHOT;
				}
			}else {
				turnStatus = TURN_SHOT;
			}
		break;
        
        case TURN_SHOT:
            if(dataBank->getShots()->size() <= 0) {
                turnStatus = TURN_PARTICLE;
                restTimer = 0.25;
                
                nextPlayer();
            }
        break;

		// This is to wait for all particles and shots to disappear before switcing turns
		case TURN_PARTICLE:
			speedTimer -= delta;
            restTimer -= delta;
			// Wait a little while to swap players
			if(restTimer <= 0.0)
				turnStatus = TURN_PLAYER;
		break;
	}
}

void GameModule::updateTimer(void)
{
    deltaAvg += delta;
	frameCount++;
	
    if((frameCount % FPS) == 0) {
    	printf("Delta average (time compression): %f (Zones: %d)\n", deltaAvg, dataBank->getBackground()->getZones()->size());
    	deltaAvg = 0.0;
    }
    
    if(dataBank->getShots()->size() == 0) {
    	speedTimer -= delta;
    }
	
	double hyperDelta = (key[KEY_TAB]) ? 7.0 : 1.0;
	
	if(gameType == GAME_DEMO) hyperDelta = 1.0;
	
	delta *= hyperDelta;
}

bool GameModule::gameOver(GameType gt)
{
	switch(gt)
	{
		case GAME_NORMAL:
			if(dataBank->getPlayerAlive() <= 1) {
				endTimer -= delta;
				if(endTimer <= 0.0)
					return true;
				else return false;
			}else return false;
		break;
		
		case GAME_DEMO:
			return true;
		break;
	}
	
	// Should never reach this
	printf("Help! Should not reach me!\n");
	return false;
}

void GameModule::nextPlayer()
{
	do {
		curPlayer++;
		if(curPlayer >= dataBank->getPlayerSize())
			curPlayer = 0;

		curPl = dataBank->getPlayer(curPlayer);
	}while(!curPl->alive() && dataBank->getPlayerAlive()>0);
}

